package service

import (
	"context"
	"fmt"
	"log"
	"strconv"
	"sync"
	"time"

	"WHY_GIN/config"
	"WHY_GIN/utils"

	"github.com/adshao/go-binance/v2"
)

// SmartStopLossOrder 智能止损订单结构
type SmartStopLossOrder struct {
	OrderID       int64     `json:"order_id"`       // 订单ID
	Symbol        string    `json:"symbol"`         // 交易对
	OriginalPrice float64   `json:"original_price"` // 原始订单价格
	Quantity      float64   `json:"quantity"`       // 订单数量
	Side          string    `json:"side"`           // 订单方向（只处理SELL）
	LossRate      float64   `json:"loss_rate"`      // 亏损比例阈值（默认0.05即5%）
	IsActive      bool      `json:"is_active"`      // 是否激活
	CreatedAt     time.Time `json:"created_at"`     // 创建时间
	LastCheckAt   time.Time `json:"last_check_at"`  // 最后检查时间
}

// SmartStopLossManager 智能止损管理器
type SmartStopLossManager struct {
	client          *binance.Client
	monitoredOrders map[int64]*SmartStopLossOrder // 监控的订单映射
	mu              sync.RWMutex                  // 读写锁
	isRunning       bool                          // 是否正在运行
	stopChan        chan struct{}                 // 停止信号
	lossThreshold   float64                       // 默认亏损阈值（5%）
	supportLevels   map[string]float64            // 支撑位价格映射（交易对 -> 支撑位价格）
	priceFilters    map[string]*binance.PriceFilter // 价格过滤器缓存
}

// NewSmartStopLossManager 创建新的智能止损管理器
func NewSmartStopLossManager() *SmartStopLossManager {
	// 初始化Binance客户端
	client := binance.NewClient(config.Cfg.Binance.APIKey, config.Cfg.Binance.SecretKey)
	if config.Cfg.Binance.UseTestnet {
		client.BaseURL = "https://testnet.binance.vision"
	}

	// 初始化时间同步
	timeSyncManager := utils.GetTimeSyncManager()
	timeSyncManager.AutoSync(client)

	return &SmartStopLossManager{
		client:          client,
		monitoredOrders: make(map[int64]*SmartStopLossOrder),
		stopChan:        make(chan struct{}),
		lossThreshold:   0.05, // 默认5%亏损阈值
		supportLevels:   make(map[string]float64), // 初始化支撑位映射
		priceFilters:    make(map[string]*binance.PriceFilter), // 初始化价格过滤器缓存
	}
}

// Start 启动智能止损监控
func (sslm *SmartStopLossManager) Start() {
	sslm.mu.Lock()
	if sslm.isRunning {
		sslm.mu.Unlock()
		return
	}
	sslm.isRunning = true
	sslm.mu.Unlock()

	log.Println("[SMART_STOP_LOSS] 启动智能止损监控服务")

	// 启动监控协程
	go sslm.monitorAllSellOrders()
}

// Stop 停止智能止损监控
func (sslm *SmartStopLossManager) Stop() {
	sslm.mu.Lock()
	defer sslm.mu.Unlock()

	if !sslm.isRunning {
		return
	}

	sslm.isRunning = false
	close(sslm.stopChan)
	log.Println("[SMART_STOP_LOSS] 停止智能止损监控服务")
}

// monitorAllSellOrders 监控所有卖单
func (sslm *SmartStopLossManager) monitorAllSellOrders() {
	ticker := time.NewTicker(5 * time.Second) // 每5秒检查一次，避免API请求过于频繁
	defer ticker.Stop()

	for {
		select {
		case <-sslm.stopChan:
			return
		case <-ticker.C:
			sslm.checkAllSellOrdersForLoss()
			sslm.checkSupportLevelBreakdown() // 检查支撑位跌破
		}
	}
}

// checkAllSellOrdersForLoss 检查所有卖单的亏损情况
func (sslm *SmartStopLossManager) checkAllSellOrdersForLoss() {
	// 获取所有未完成的订单
	allOpenOrders, err := sslm.getAllOpenOrders()
	if err != nil {
		log.Printf("[SMART_STOP_LOSS] 获取未完成订单失败: %v", err)
		return
	}

	// 过滤出卖单
	sellOrders := sslm.filterSellOrders(allOpenOrders)
	if len(sellOrders) == 0 {
		return
	}

	log.Printf("[SMART_STOP_LOSS] 检查 %d 个卖单的亏损情况", len(sellOrders))

	// 获取所有需要的交易对价格
	symbols := make(map[string]bool)
	for _, order := range sellOrders {
		symbols[order.Symbol] = true
	}

	// 批量获取当前市场价格
	currentPrices, err := sslm.getCurrentMarketPrices(symbols)
	if err != nil {
		log.Printf("[SMART_STOP_LOSS] 获取市场价格失败: %v", err)
		return
	}

	// 检查每个卖单的亏损情况
	for _, order := range sellOrders {
		currentPrice, exists := currentPrices[order.Symbol]
		if !exists {
			continue
		}

		// 计算亏损比例
		orderPrice, err := strconv.ParseFloat(order.Price, 64)
		if err != nil {
			continue
		}

		// 对于卖单，如果当前市价低于订单价格，说明可能亏损
		// 亏损比例 = (订单价格 - 当前市价) / 订单价格
		lossRate := (orderPrice - currentPrice) / orderPrice

		if lossRate >= sslm.lossThreshold {
			log.Printf("[SMART_STOP_LOSS] 发现亏损卖单: OrderID=%d, Symbol=%s, 订单价=%.8f, 市价=%.8f, 亏损=%.2f%%",
				order.OrderID, order.Symbol, orderPrice, currentPrice, lossRate*100)

			// 执行止损（以限价卖出）
			go sslm.executeLimitSellStopLoss(order, currentPrice, lossRate)
		}
	}
}

// getAllOpenOrders 获取所有未完成的订单
func (sslm *SmartStopLossManager) getAllOpenOrders() ([]*binance.Order, error) {
	return sslm.client.NewListOpenOrdersService().Do(context.Background())
}

// filterSellOrders 过滤出卖单
func (sslm *SmartStopLossManager) filterSellOrders(orders []*binance.Order) []*binance.Order {
	var sellOrders []*binance.Order
	for _, order := range orders {
		if order.Side == binance.SideTypeSell && order.Type == binance.OrderTypeLimit {
			sellOrders = append(sellOrders, order)
		}
	}
	return sellOrders
}

// getCurrentMarketPrices 获取当前市场价格
func (sslm *SmartStopLossManager) getCurrentMarketPrices(symbols map[string]bool) (map[string]float64, error) {
	// 使用ListPrices接口获取所有价格
	prices, err := sslm.client.NewListPricesService().Do(context.Background())
	if err != nil {
		return nil, fmt.Errorf("获取价格列表失败: %v", err)
	}

	result := make(map[string]float64)
	for _, price := range prices {
		if symbols[price.Symbol] {
			priceFloat, err := strconv.ParseFloat(price.Price, 64)
			if err != nil {
				continue
			}
			result[price.Symbol] = priceFloat
		}
	}

	return result, nil
}

// executeLimitSellStopLoss 执行限价卖出止损（滑点不超过1%）
func (sslm *SmartStopLossManager) executeLimitSellStopLoss(order *binance.Order, currentPrice, lossRate float64) {
	log.Printf("[SMART_STOP_LOSS] 开始执行限价止损: OrderID=%d, Symbol=%s, 亏损=%.2f%%",
		order.OrderID, order.Symbol, lossRate*100)

	// 首先取消原限价卖单
	err := sslm.cancelOrder(order.OrderID, order.Symbol)
	if err != nil {
		log.Printf("[SMART_STOP_LOSS] 取消原订单失败: %v", err)
		return
	}

	log.Printf("[SMART_STOP_LOSS] 原限价卖单已取消: OrderID=%d", order.OrderID)

	// 等待一小段时间确保订单取消生效
	time.Sleep(1 * time.Second)

	// 执行市价卖单
	quantity, err := strconv.ParseFloat(order.OrigQuantity, 64)
	if err != nil {
		log.Printf("[SMART_STOP_LOSS] 解析订单数量失败: %v", err)
		return
	}

	// 获取已成交数量，计算剩余数量
	executedQty, err := strconv.ParseFloat(order.ExecutedQuantity, 64)
	if err != nil {
		log.Printf("[SMART_STOP_LOSS] 解析已成交数量失败: %v", err)
		return
	}

	remainingQty := quantity - executedQty
	if remainingQty <= 0 {
		log.Printf("[SMART_STOP_LOSS] 订单已完全成交，无需止损")
		return
	}

	// 计算限价止损价格（当前市价减去1%滑点）
	stopLossPrice := currentPrice * 0.99 // 1%滑点保护

	// 下限价卖单
	err = sslm.placeLimitSellOrder(order.Symbol, remainingQty, stopLossPrice)
	if err != nil {
		log.Printf("[SMART_STOP_LOSS] 执行限价卖单失败: %v", err)
		return
	}

	log.Printf("[SMART_STOP_LOSS] 限价止损执行成功: Symbol=%s, 数量=%.8f, 原价=%.8f, 市价=%.8f, 止损价=%.8f, 亏损=%.2f%%",
		order.Symbol, remainingQty, order.Price, currentPrice, stopLossPrice, lossRate*100)

	// 发送止损事件通知
	if GlobalStopLossEventService != nil {
		event := StopLossEvent{
			OrderID:   order.OrderID,
			Symbol:    order.Symbol,
			LossRate:  lossRate,
			Timestamp: time.Now(),
		}
		GlobalStopLossEventService.NotifyStopLossTriggered(event)
		log.Printf("[SMART_STOP_LOSS] 已发送止损事件通知: OrderID=%d, Symbol=%s", order.OrderID, order.Symbol)
	} else {
		log.Printf("[SMART_STOP_LOSS] 警告: 止损事件服务未初始化，无法发送通知")
	}
}

// cancelOrder 取消订单
func (sslm *SmartStopLossManager) cancelOrder(orderID int64, symbol string) error {
	_, err := sslm.client.NewCancelOrderService().
		Symbol(symbol).
		OrderID(orderID).
		Do(context.Background())
	return err
}

// placeLimitSellOrder 下限价卖单
func (sslm *SmartStopLossManager) placeLimitSellOrder(symbol string, quantity, price float64) error {
	// 获取交易对的价格过滤器
	tickSize, err := sslm.GetTickSize(symbol)
	if err != nil {
		return fmt.Errorf("获取价格精度失败: %v", err)
	}
	
	// 使用现有的价格精度调整函数
	return PlaceLimitOrderWithFloatQuantity(sslm.client, symbol, binance.SideTypeSell, price, quantity, tickSize)
}

// GetTickSize 获取交易对的价格精度
func (sslm *SmartStopLossManager) GetTickSize(symbol string) (string, error) {
	sslm.mu.RLock()
	// 检查缓存
	if filter, exists := sslm.priceFilters[symbol]; exists {
		sslm.mu.RUnlock()
		return filter.TickSize, nil
	}
	sslm.mu.RUnlock()
	
	// 获取交易对信息
	exchangeInfo, err := sslm.client.NewExchangeInfoService().Do(context.Background())
	if err != nil {
		return "", err
	}
	
	for _, symbolInfo := range exchangeInfo.Symbols {
		if symbolInfo.Symbol == symbol {
			priceFilter := symbolInfo.PriceFilter()
			if priceFilter != nil {
				// 缓存价格过滤器
				sslm.mu.Lock()
				sslm.priceFilters[symbol] = priceFilter
				sslm.mu.Unlock()
				return priceFilter.TickSize, nil
			}
		}
	}
	
	return "", fmt.Errorf("未找到%s的价格过滤器", symbol)
}

// SetLossThreshold 设置亏损阈值
func (sslm *SmartStopLossManager) SetLossThreshold(threshold float64) {
	sslm.mu.Lock()
	defer sslm.mu.Unlock()
	sslm.lossThreshold = threshold
	log.Printf("[SMART_STOP_LOSS] 亏损阈值已设置为: %.2f%%", threshold*100)
}

// GetLossThreshold 获取当前亏损阈值
func (sslm *SmartStopLossManager) GetLossThreshold() float64 {
	sslm.mu.RLock()
	defer sslm.mu.RUnlock()
	return sslm.lossThreshold
}

// GetMonitoringStatus 获取监控状态
func (sslm *SmartStopLossManager) GetMonitoringStatus() map[string]interface{} {
	sslm.mu.RLock()
	defer sslm.mu.RUnlock()

	return map[string]interface{}{
		"is_running":      sslm.isRunning,
		"loss_threshold":  sslm.lossThreshold,
		"monitored_count": len(sslm.monitoredOrders),
		"last_check":      time.Now().Format("2006-01-02 15:04:05"),
	}
}

// 全局智能止损管理器实例
var GlobalSmartStopLossManager *SmartStopLossManager

// InitSmartStopLossManager 初始化全局智能止损管理器
func InitSmartStopLossManager() {
	GlobalSmartStopLossManager = NewSmartStopLossManager()
	GlobalSmartStopLossManager.Start()
	log.Println("[SMART_STOP_LOSS] 全局智能止损管理器初始化完成")
}

// 便捷函数

// SetSmartStopLossThreshold 设置智能止损阈值（便捷函数）
func SetSmartStopLossThreshold(threshold float64) error {
	if GlobalSmartStopLossManager == nil {
		return fmt.Errorf("智能止损管理器未初始化")
	}
	GlobalSmartStopLossManager.SetLossThreshold(threshold)
	return nil
}

// GetSmartStopLossStatus 获取智能止损状态（便捷函数）
func GetSmartStopLossStatus() map[string]interface{} {
	if GlobalSmartStopLossManager == nil {
		return map[string]interface{}{
			"error": "智能止损管理器未初始化",
		}
	}
	return GlobalSmartStopLossManager.GetMonitoringStatus()
}

// StopSmartStopLossManager 停止智能止损管理器（便捷函数）
func StopSmartStopLossManager() {
	if GlobalSmartStopLossManager != nil {
		GlobalSmartStopLossManager.Stop()
		log.Println("[SMART_STOP_LOSS] 全局智能止损管理器已停止")
	}
}

// SetSupportLevel 设置支撑位价格
func (sslm *SmartStopLossManager) SetSupportLevel(symbol string, price float64) {
	sslm.mu.Lock()
	defer sslm.mu.Unlock()
	sslm.supportLevels[symbol] = price
	log.Printf("[SMART_STOP_LOSS] 设置支撑位: %s = %.8f", symbol, price)
}

// RemoveSupportLevel 移除支撑位
func (sslm *SmartStopLossManager) RemoveSupportLevel(symbol string) {
	sslm.mu.Lock()
	defer sslm.mu.Unlock()
	delete(sslm.supportLevels, symbol)
	log.Printf("[SMART_STOP_LOSS] 移除支撑位: %s", symbol)
}

// GetSupportLevel 获取支撑位价格
func (sslm *SmartStopLossManager) GetSupportLevel(symbol string) (float64, bool) {
	sslm.mu.RLock()
	defer sslm.mu.RUnlock()
	price, exists := sslm.supportLevels[symbol]
	return price, exists
}

// GetAllSupportLevels 获取所有支撑位
func (sslm *SmartStopLossManager) GetAllSupportLevels() map[string]float64 {
	sslm.mu.RLock()
	defer sslm.mu.RUnlock()
	result := make(map[string]float64)
	for symbol, price := range sslm.supportLevels {
		result[symbol] = price
	}
	return result
}

// checkSupportLevelBreakdown 检查支撑位跌破
func (sslm *SmartStopLossManager) checkSupportLevelBreakdown() {
	sslm.mu.RLock()
	if len(sslm.supportLevels) == 0 {
		sslm.mu.RUnlock()
		return
	}
	
	// 复制支撑位映射以避免长时间持有锁
	supportLevelsCopy := make(map[string]float64)
	for symbol, price := range sslm.supportLevels {
		supportLevelsCopy[symbol] = price
	}
	sslm.mu.RUnlock()
	
	// 获取当前市场价格
	symbols := make(map[string]bool)
	for symbol := range supportLevelsCopy {
		symbols[symbol] = true
	}
	
	currentPrices, err := sslm.getCurrentMarketPrices(symbols)
	if err != nil {
		log.Printf("[SMART_STOP_LOSS] 获取市场价格失败: %v", err)
		return
	}
	
	// 检查每个交易对的支撑位
	for symbol, supportPrice := range supportLevelsCopy {
		currentPrice, exists := currentPrices[symbol]
		if !exists {
			continue
		}
		
		// 如果当前价格跌破支撑位
		if currentPrice < supportPrice {
			breakdownRate := (supportPrice - currentPrice) / supportPrice
			log.Printf("[SMART_STOP_LOSS] 支撑位跌破! %s: 当前价格 %.8f < 支撑位 %.8f，跌破幅度 %.2f%%", symbol, currentPrice, supportPrice, breakdownRate*100)
			
			// 触发支撑位跌破事件
			if GlobalStopLossEventService != nil {
				event := SupportLevelBreakdownEvent{
					Symbol:        symbol,
					SupportLevel:  supportPrice,
					CurrentPrice:  currentPrice,
					BreakdownRate: breakdownRate,
					Timestamp:     time.Now(),
				}
				GlobalStopLossEventService.NotifySupportLevelBreakdown(event)
			}
			
			// 移除已跌破的支撑位，避免重复触发
			sslm.RemoveSupportLevel(symbol)
		}
	}
}

// 便捷函数 - 支撑位管理

// SetSupportLevelForSymbol 设置指定交易对的支撑位（便捷函数）
func SetSupportLevelForSymbol(symbol string, price float64) error {
	if GlobalSmartStopLossManager == nil {
		return fmt.Errorf("智能止损管理器未初始化")
	}
	GlobalSmartStopLossManager.SetSupportLevel(symbol, price)
	return nil
}

// RemoveSupportLevelForSymbol 移除指定交易对的支撑位（便捷函数）
func RemoveSupportLevelForSymbol(symbol string) error {
	if GlobalSmartStopLossManager == nil {
		return fmt.Errorf("智能止损管理器未初始化")
	}
	GlobalSmartStopLossManager.RemoveSupportLevel(symbol)
	return nil
}

// GetSupportLevelForSymbol 获取指定交易对的支撑位（便捷函数）
func GetSupportLevelForSymbol(symbol string) (float64, bool, error) {
	if GlobalSmartStopLossManager == nil {
		return 0, false, fmt.Errorf("智能止损管理器未初始化")
	}
	price, exists := GlobalSmartStopLossManager.GetSupportLevel(symbol)
	return price, exists, nil
}

// GetAllSupportLevelsStatus 获取所有支撑位状态（便捷函数）
func GetAllSupportLevelsStatus() map[string]interface{} {
	if GlobalSmartStopLossManager == nil {
		return map[string]interface{}{
			"error": "智能止损管理器未初始化",
		}
	}
	
	supportLevels := GlobalSmartStopLossManager.GetAllSupportLevels()
	return map[string]interface{}{
		"support_levels": supportLevels,
		"count":          len(supportLevels),
		"last_check":     time.Now().Format("2006-01-02 15:04:05"),
	}
}
